//
//  DepartureFetcher.m
//  TrainTrack
//
//  Created by Jonathan Bunde-Pedersen on 04/10/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "Model.h"
#import "Departure.h"
#import "DepartureWalker.h"

@implementation Model

@synthesize database, departures, stations, favouriteStations;

- (NSArray *) fetchValidDeparturesForStation:(NSString *)station {
	NSArray *allDepartures = [self fetchDeparturesForStation:station];
	NSArray *validDepartures = [DepartureWalker findValidDepartures:allDepartures];
	
	return validDepartures;
}

- (NSArray *) fetchDeparturesForStation:(NSString *)station {
	sqlite3_stmt *refresh_statement = nil;
	
	if(self.departures == nil)
		self.departures = [NSMutableArray array];
	else
		[self.departures removeAllObjects];
	
	const char *sql;
	
	int weekday = 1;
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"e"];
	// get the current day name
	NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
	NSLog(@"day name: %@", dateString);
	[dateFormatter release];


	if ([dateString isEqualToString:@"6"]) {
		NSLog(@"Day for schedule is a Saturday");
		weekday = 2;
	} else if ([dateString isEqualToString:@"7"]) {
		NSLog(@"Day for schedule is a Sunday");
		weekday = 3;
	} else {
		NSLog(@"Day for schedule is a weekday");
		weekday = 1;
	}
	
	NSString *ns_sql = [NSString stringWithFormat:@"SELECT station, line, direction, minute, weekday, earliest_departure, latest_departure FROM Departures WHERE station = \"%@\" and weekday=%d ORDER BY minute", station, weekday];

	//ns_sql = [ns_sql stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // trim
	
	sql = [ns_sql UTF8String];
	
	NSLog(ns_sql);
	
	if (sqlite3_prepare_v2(database, sql, -1, &refresh_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	
	while (sqlite3_step(refresh_statement) == SQLITE_ROW) {
		Departure *departure = [[Departure alloc] init];
		
		// stations
		char *str = (char *)sqlite3_column_text(refresh_statement, 0);
		departure.station  = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		// line
		str = (char *)sqlite3_column_text(refresh_statement, 1);
		departure.line  = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		// direction
		str = (char *)sqlite3_column_text(refresh_statement, 2);
		departure.direction = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		// minute
		departure.minute = sqlite3_column_int(refresh_statement,3);
		
		// weekday
		departure.weekday = sqlite3_column_int(refresh_statement,4);
		
		// earliest
		departure.earliest_departure = sqlite3_column_int(refresh_statement,5);
		// cheap trick to better deal with earliest departures on the next day, this only applies
		// to the last few trains. luckily trains don't start running just past midnight
		if (departure.earliest_departure < 100) {
			departure.earliest_departure += 2400;
		}
		
		// latest
		departure.latest_departure = sqlite3_column_int(refresh_statement,6);
		// cheap trick to better deal with latest departures on the next day
		if (departure.latest_departure < 100) {
			departure.latest_departure += 2400;
		}
		
		[self.departures addObject:departure];
		
		[departure release];
	} 
	
	sqlite3_finalize(refresh_statement);
	
	return self.departures;
}

- (NSArray *) fetchStations {
	sqlite3_stmt *refresh_statement = nil;
	
	// lazy initialization of emails array
	
	if(self.stations == nil)
		self.stations = [NSMutableArray array];
	else
		return self.stations;
	
	// Compile the refresh statement, if needed.
	//if (refresh_statement == nil) {
	const char *sql;
	
	
	NSString *ns_sql = @"SELECT DISTINCT station FROM Departures ORDER BY station";
	//ns_sql = [ns_sql stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // trim
	
	sql = [ns_sql UTF8String];
	
	if (sqlite3_prepare_v2(database, sql, -1, &refresh_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	
	while (sqlite3_step(refresh_statement) == SQLITE_ROW) {
		
		char *str = (char *)sqlite3_column_text(refresh_statement, 0);
		NSString *station  = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		[self.stations addObject:station];
		
		//[station release];
	} 
	
	sqlite3_finalize(refresh_statement);
	
	return self.stations;
}

- (NSArray *) fetchFavouriteStations {
	sqlite3_stmt *refresh_statement = nil;
	
	// lazy initialization of emails array
	
	if(self.favouriteStations == nil)
		self.favouriteStations = [NSMutableArray array];
	else
		[self.favouriteStations removeAllObjects];
	
	
	// Compile the refresh statement, if needed.
	//if (refresh_statement == nil) {
	const char *sql;
	
	
	NSString *ns_sql = @"SELECT DISTINCT station FROM FavouriteStations";
	//ns_sql = [ns_sql stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // trim
	
	sql = [ns_sql UTF8String];
	
	if (sqlite3_prepare_v2(database, sql, -1, &refresh_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	
	while (sqlite3_step(refresh_statement) == SQLITE_ROW) {
		
		char *str = (char *)sqlite3_column_text(refresh_statement, 0);
		NSString *station  = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		[self.favouriteStations addObject:station];
	} 
	
	sqlite3_finalize(refresh_statement);
	
	return self.favouriteStations;
}



@end
